<template>
  <!--关联商品-->
  <el-dialog
    title="关联商品"
    :visible="showModal"
    :modal-append-to-body="false"
    width="60%"
    top="5vh"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <el-row>
      <el-form ref="queryData" :model="queryData" label-width="100px">
        <el-row type="flex" :gutter="20">
          <el-col :span="8">
            <el-form-item label="商品分类" prop="categoryName">
              <el-input
                v-model="queryData.categoryName"
                placeholder="请输入商品分类"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="SPU编码" prop="spuNo">
              <el-input
                v-model="queryData.spuNo"
                placeholder="请输入SPU编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="SKU编码" prop="skuNo">
              <el-input
                v-model="queryData.skuNo"
                placeholder="请输入SKU编码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" :gutter="20" class="row-bg">
          <el-col :span="8">
            <el-form-item label="商品名称" prop="productName">
              <el-input
                v-model="queryData.productName"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="showSupplyInput">
            <el-form-item label="供应商编码" prop="supplyUuid">
              <el-input
                v-model="queryData.supplyUuid"
                placeholder="请输入供应商编码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="end">
          <el-button
              :disabled="tabpaneDisabled"
              type="primary"
              @click="handleQueryData"
              >查询</el-button
            >
            <el-button
              :disabled="tabpaneDisabled"
              @click="handleResetData('queryData')"
              >清空</el-button
            >
            <el-button
              v-if="tabsStatus === 'notAssociated' ? true : false"
              type="primary"
              ghost
              @click="handleBatchAssociate"
              :disabled="tabpaneDisabled"
              >批量关联</el-button
            >
            <el-button
              v-else
              ghost
              @click="handleBatchCancel"
              :disabled="tabpaneDisabled"
              >批量取消</el-button
            >
        </el-row>
      </el-form>
    </el-row>
    <el-tabs
      v-model="tabsStatus"
      @tab-click="handleClickTabs"
      style="margin: 10px"
    >
      <el-tab-pane
        label="未关联"
        name="notAssociated"
        :disabled="tabpaneDisabled"
      >
      </el-tab-pane>
      <el-tab-pane
        label="已关联"
        name="isAssociated"
        :disabled="tabpaneDisabled"
      >
      </el-tab-pane>
    </el-tabs>
    <pl-table
      ref="multipleTable"
      size="mini"
      :row-height="45"
      border="border"
      use-virtual
      height="480"
      v-loading="tableLoading"
      :data="dataSource"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
      @selection-change="handleCheckTableItem"
    >
      <!-- <pl-table-column fixed type="selection" width="50" /> -->
      <pl-table-column
        v-for="column in columns"
        :key="column.key"
        :prop="column.key"
        :label="column.title"
        :property="column.key"
        :align="column.align"
        :min-width="100"
        :fixed="column.fixed"
        :show-overflow-tooltip="true"
        :type="column.type"
      >
        <template v-if="column.slot === 'action'" v-slot="scope">
          <el-button
            v-if="tabsStatus === 'notAssociated'"
            type="success"
            size="mini"
            @click="handleAssociateGoods(scope.row, scope.$index)"
            >关联</el-button
          >
          <el-button
            v-else
            size="mini"
            @click="handleCancelGoods(scope.row, scope.$index)"
            >取消</el-button
          >
        </template>
      </pl-table-column>
    </pl-table>
    <div class="pagination_wrap">
      <el-pagination
        background
        :total="totalPage"
        :current-page="nowPage"
        :page-size="pageShow"
        :page-sizes="pageSizeOpts"
        @current-change="handleChangePage"
        @size-change="handleChangePageSize"
        layout="total, sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </div>
    <el-row slot="footer" style="text-align: center">
      <el-button type="primary" @click="handleCloseModal">返回表单</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { getValueFn } from './utils';
import skuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/skuDimension';
export default {
  mixins: [skuDimensionMixins],
  props: {
    /* 表格表头 */
    columns: {
      type: Array,
      required: true
    },
    /* 请求查询数据接口入参 */
    requestParams: {
      type: Array,
      required: true
    },
    /* 请求查询数据接口区别未关联和已关联的入参 */
    distinctParams: {
      type: Object
    },
    /* 查询接口及类型 */
    requestApi: {
      type: Object,
      required: true
    },
    /* 是否选择供应商 */
    supplyCode: {
      type: String
    },
    pageSizeOpts: {
      type: Array,
      default () {
        return [10, 100, 500, 1000];
      }
    },
    associatedSkuIdName: {
      type: String,
      default: 'skuNo'
    }
  },
  data () {
    return {
      /* 商品维度
        共有： 商品分类 categoryName
              商品名称 productName
              SPU编码 spuNo
        SKU维度：SKU编码 skuNo
      */
      queryData: {
        spuNo: '', // spu编码
        productName: '', // 商品名称
        categoryName: '', // 商品分类
        skuNo: '', // SKU编码
        supplyUuid: '', // 供应商编码
      },
      dataSource: [], // 表格数据
      tabsStatus: 'notAssociated', // 当前tabs页签
      nowPage: 1, // 当前页
      pageShow: 10, // 每页条数
      totalPage: 0, // 总条数
      tableLoading: false,
      checkTableItemList: [],
      isQueryRel: false,
      tabpaneDisabled: false
    };
  },
  computed: {
    showSupplyInput () {
      return this.requestParams.some(item => item.name == 'supplyUuid')
    }
  },
  beforeDestroy () {
    this.DESTORY_STATE();
  },
  methods: {
    /* 切换关联和未关联 */
    handleClickTabs () {
      if (this.getListFromMapFn().length === 0) {
        this.totalPage = 0;
      }
      this.nowPage = 1;
      this.getDataListAction();
    },
    /* 获取数据方法 */
    getDataListAction () {
      // let skuList = [...this.associatedSkuIdList]
      let rowList = this.getListFromMapFn();
      let skuList = this.getSkuNoListFn(rowList);
      let param = _.cloneDeep(this.requestParams);
      param.forEach((value) => {
        value.value = getValueFn(value, this.queryData);
      });
      let { url, type } = this.requestApi;
      let requsetUrl = '';
      if (this.tabsStatus === 'notAssociated') {
        let distinctParamsNotAssociated = _.cloneDeep(
          this.distinctParams.notAssociated
        );
        let i = _.findIndex(distinctParamsNotAssociated, (value) => {
          return !value.value;
        });
        distinctParamsNotAssociated[i].value = skuList.join(',');
        param.push(...distinctParamsNotAssociated);
        requsetUrl = url[0];
        this.isQueryRel = false;
      } else {
        let distinctParamsAssociated = _.cloneDeep(
          this.distinctParams.associated
        );
        let i = _.findIndex(distinctParamsAssociated, (value) => {
          return !value.value;
        });
        distinctParamsAssociated[i].value = skuList.join(',');
        param.push(...distinctParamsAssociated);
        requsetUrl = url[1] ? url[1] : url[0];
        this.isQueryRel = true;
      }
      let data = {
        sortName: '',
        sortType: '',
        searchParam: JSON.stringify(param),
        nowPage: this.nowPage,
        pageShow: this.pageShow
      };
      if (this.supplyCode) {
        data.supplyCode = this.supplyCode;
        data.isQueryRel = this.isQueryRel;
      }
      if (skuList.length === 0 && this.tabsStatus === 'isAssociated') {
        this.dataSource = [];
        return;
      }
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.tableLoading = true;
      this.tabpaneDisabled = true;
      ApiRequest(requsetUrl, type, data, false)
        .then((res) => {
          if (res.retStatus === '1' && res.retData.results) {
            this.dataSource = res.retData.results;
            this.totalPage = res.retData.totalNum;
          } else {
            this.dataSource = [];
            this.totalPage = res.retData.totalNum;
          }
          this.tableLoading = false;
          this.tabpaneDisabled = false;
        })
        .catch(() => {
          this.tableLoading = false;
          this.tabpaneDisabled = false;
        });
    },
    /* 查询方法 */
    handleQueryData () {
      this.getDataListAction();
    },
    /* 清空方法 */
    handleResetData (name) {
      this.$refs[name].resetFields();
    },
    /* 批量关联方法 */
    handleBatchAssociate () {
      if (this.checkTableItemList.length === 0) {
        return;
      }
      this.checkTableItemList.forEach((value) => {
        this.ASSOCIATED_GOODS({ row: value, type: this.associatedSkuIdName });
      });
      this.$nextTick(() => {
        this.getDataListAction();
      });
    },
    /* 批量取消方法 */
    handleBatchCancel () {
      if (this.checkTableItemList.length === 0) {
        return;
      }
      this.checkTableItemList.forEach((value) => {
        this.CANCEL_GOODS({ row: value, type: this.associatedSkuIdName });
      });
      this.$nextTick(() => {
        this.getDataListAction();
      });
    },
    /* 关联方法 */
    handleAssociateGoods (row, index) {
      this.ASSOCIATED_GOODS({ row, type: this.associatedSkuIdName });
      this.getDataListAction();
    },
    /* 取消方法 */
    handleCancelGoods (row, index) {
      this.CANCEL_GOODS({ row, type: this.associatedSkuIdName });
      this.getDataListAction();
    },
    /* 表格数据勾选或勾选取消方法 */
    handleCheckTableItem (list) {
      this.checkTableItemList = list;
    },
    handleChangePage (page) {
      this.nowPage = page;
      this.getDataListAction();
    },
    handleChangePageSize (size) {
      this.nowPage = 1;
      this.pageShow = size;
      this.getDataListAction();
    },
    handleCloseModal () {
      this.nowPage = 1;
      this.pageShow = 10;
      this.tabsStatus = 'notAssociated';
      this.handleResetData('queryData');
      this.dataSource = [];
      this.$emit('submitAction');
      this.CHANGE_MODAL_SWITCH(false);
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .el-dialog__body {
  padding: 10px 20px;
}
/deep/ .el-dialog__header {
  border-bottom: 1px solid #e8eaec;
}
/deep/ .el-dialog__footer {
  border-top: 1px solid #e8eaec;
}
/* 查询清空批量操作栏样式 */
.options_wrap {
  /deep/ .ivu-btn {
    margin-left: 15px;
  }
  /deep/ .ivu-btn-ghost {
    margin-right: 10px;
  }
}

/* 分页样式 */
.pagination_wrap {
  text-align: center;
  margin-top: 10px;
}
</style>
